
#include <librally.h>

#include "heartbeat.h"

void* rp_rstatd_hb(void *arg)
{
	char fname[] = "rp_rstatd_hb";
	char msg[] = "fatal error";
	Err err;
	struct event_base *evbase;
	struct event *ev;
	struct event *ev2;

	err = rp_mutex_lock(&g_mutex_rstatd_hb);
	// setup TCP connection with rindexd
	err = rp_comm_tcp_connect(&g_addr_rindexd, &g_fd_rindexd);
	if (!err) 
	{
		rp_log(LOG_FATAL, fname, "Cannot connect with rindexd");
		err = rp_mutex_unlock(&g_mutex_rstatd_hb);
		return NULL;
	}
	
	evbase = event_init();
	evtimer_set(ev, rp_rstatd_hb_info, NULL);
	if (evtimer_add(ev, &g_timeval_rstatd_hb) < 0)
	{
		rp_log(LOG_FATAL, fname, "Adding timer event failed");
		return NULL;
	}
	event_set(ev2, g_fd_rindexd, EV_READ, rp_rstatd_hb_cmd, NULL);
	event_add(ev2, NULL);
	event_loop(EVLOOP_NONBLOCK);

	err = rp_comm_tcp_close(&g_fd_rindexd);		
	
	err = rp_mutex_unlock(&g_mutex_rstatd_hb);
	return NULL;
}

void rp_rstatd_hb_info(int fd, short event, void *arg)
{
	char fname[] = "rp_rstatd_hb_timer";
	char msg[] = "fatal error";
	Err err;

	if (!rp_rstatd_scoreboard_total(&g_scoreboard_rstatd))
	{
		rp_log(LOG_DEBUG, fname, "Scoreboard is empty, exit from the event loop....");
		// exit event dispatch
		//event_loopbreak();
		struct timeval time;
		time.tv_sec = 0;       /* seconds */
		time.tv_usec = 0;      /* microseconds */

		event_loopexit(&time);
	}

	static Info info;
	err = rp_rstatd_info(&info);
	if (!err)
	{
		rp_log(LOG_CRITICAL, fname, "Failed to collect te host information");
		return;
	}

	err = rp_comm_send(g_fd_rindexd, &info, sizeof(info));
	if (!err)
	{
		rp_log(LOG_CRITICAL, fname, "Failed to send the host information to rindexd");
		return;
	}

	return;
}

void rp_rstatd_hb_cmd(int fd, short event, void *arg)
{
	char fname[] = "rp_rstatd_hb_cmd";
	char msg[] = "fatal error";
	Err err;
	static Cmd cmd;

	err = rp_comm_recv(g_fd_rindexd, &cmd, sizeof(cmd));
	if (!err)
	{
		rp_log(LOG_CRITICAL, fname, msg);
		return;
	}

	err = rp_cqueue_put(&g_cqueue_rstatd_cmd, &cmd);

	return;	
}




